import java.util.*;

public class 腐烂的苹果 {
    /*
    https://www.nowcoder.com/practice/54ab9865ce7a45968b126d6968a77f34?tpId=196&tqId=40529&ru=/exam/oj
    复习了一下多源bfs
     */
    public int rotApple (ArrayList<ArrayList<Integer>> grid) {
        // write code here
        int n = grid.size();
        int m = grid.get(0).size();
        int ret = -1;
        int[] dx = {0,0,1,-1};
        int[] dy = {1,-1,0,0};
        boolean[][] vis = new boolean[n][m];
        Queue<int[]> q = new LinkedList<>();
        for(int i = 0;i < n;i++){
            for(int j = 0;j < m;j++){
                if(grid.get(i).get(j) == 2){
                    q.add(new int[]{i,j});
                }
            }
        }
        while(!q.isEmpty()){
            int size = q.size();
            while(size-- != 0){
                int[] t = q.poll();
                int a = t[0];
                int b = t[1];
                for(int i = 0;i < 4;i++){
                    int x = a + dx[i];
                    int y = b + dy[i];
                    if(x >= 0 && x < n && y >= 0 && y < m && !vis[x][y] && grid.get(x).get(y) == 1){
                        vis[x][y] = true;
                        q.add(new int[]{x,y});
                    }
                }
            }
            ret++;
        }
        for(int i = 0;i < n;i++){
            for(int j = 0;j < m;j++){
                if(!vis[i][j] && grid.get(i).get(j) == 1){
                    return -1;
                }
            }
        }
        return ret;
    }
    public static void main(String[] args) {

    }
}
